package org.example.buysystem.service;

import cn.hutool.core.io.FileUtil;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.xml.fastinfoset.stax.events.Util;
import org.example.buysystem.constants.Constants;
import org.example.buysystem.entity.MyFile;
import org.example.buysystem.exception.ServiceException;
import org.example.buysystem.mapper.FileMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@Service
public class FileService extends ServiceImpl<FileMapper, MyFile> {


    private final FileMapper fileMapper;

    public FileService(FileMapper fileMapper) {
        this.fileMapper = fileMapper;
        }


    public void download(String fileName, HttpServletResponse response){
        File file = new File(Constants.fileFolderPath + fileName);

        if(!file.exists()){
            throw new ServiceException(Constants.CODE_500,"文件不存在");
        }

        try{
            ServletOutputStream os =response.getOutputStream();
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
            response.setContentType("application/octet-stream");
            os.write(FileUtil.readBytes(file));
            os.flush();
            os.close();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    public String upload(MultipartFile uploadFile) {

        String originalFilename = uploadFile.getOriginalFilename();
        String type=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        long size=uploadFile.getSize();
        String url;
        MyFile myFile = new MyFile();
        myFile.setName(originalFilename);
        myFile.setType(type);
        myFile.setSize(size);

        //通过md5加密
        InputStream inputStream = null;

        try{
            inputStream = uploadFile.getInputStream();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
        String md5 = SecureUtil.md5(inputStream);

        QueryWrapper<MyFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<MyFile> list = fileMapper.selectList(queryWrapper);
        if(list.size()!=0){
            url=list.get(0).getUrl();
            myFile.setUrl(url);
        }else {

            File folder = new File(Constants.fileFolderPath);
            if (!folder.exists()) {
                folder.mkdir();
            }
            String folderPath = folder.getAbsolutePath() + "/";
            System.out.println("文件地址为" + folderPath);

            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();

            String finalFileName = uuid + "." + type;
            File targetFile = new File(folderPath + finalFileName);

            try {
                uploadFile.transferTo(targetFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            url = "/file/" + finalFileName;
            myFile.setUrl(url);
        }
        myFile.setMd5(md5);
            fileMapper.insert(myFile);
            System.out.println("文件"+originalFilename+""+url);
        
        return url;

        }


    public IPage<MyFile> selectPage(int pageNum, int pageSize, String fileName) {
        IPage<MyFile> page = new Page<>(pageNum, pageSize);
        QueryWrapper<MyFile> queryWrapper = new QueryWrapper<>();
        if(!Util.isEmptyString(fileName)){
            queryWrapper.like("name", fileName);

        }
        queryWrapper.eq("is_delete",false);
        queryWrapper.orderByDesc("id");
        return page(page, queryWrapper);



    }

    public int fakedelete(Integer id) {
        UpdateWrapper<MyFile> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("is_delete", true);
        return fileMapper.update(null, updateWrapper);

    }
}




